package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @Author Yang
 * @Date 2023/3/1 17:07
 */
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private HttpSession session;

    @Override
    public Employee login(String username, String password) {
        //1. 根据账号查询
        Employee employee = employeeMapper.findByUsername(username);

        //2. 如果账号不存在
        if (employee == null) {
//            return ResultInfo.error("账号不存在");
            throw new CustomException("账号不存在");
        }
        //3. 将密码隐蔽
        String Pwd = SecureUtil.md5(password);

        //4. 如果密码不同返回
        if (!StrUtil.equals(Pwd, employee.getPassword())) {
//            return ResultInfo.error("密码错误");
            throw new CustomException("密码错误");
        }

        //5. 如果账号停止
        if (employee.getStatus() != 1) {
//            return ResultInfo.error("账号停止使用");
            throw new CustomException("账号停止使用");
        }

        //6. 登陆成功下发session
        session.setAttribute(Constant.SESSION_EMPLOYEE,employee);

        //7. 返回
        return employee;
    }

    @Override
    public List<Employee> find(String name) {
        List<Employee> list = employeeMapper.find(name);
        return list;
    }

    //新增员工
    @Override
    public void save(Employee employee) {
//        //员工id
//        long id = IdUtil.createSnowflake(1, 1).nextId();
//        employee.setId(id);

        //员工密码
        String md5 = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(md5);

        //员工状态
        employee.setStatus(Employee.STATUS_ENABLE);

        //调用Mapper
        employeeMapper.insert(employee);
    }

    //ID回显
    @Override
    public Employee findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        return employee;
    }

    @Override
    public void update(Employee employee) {
//        //修改的时间
//        employee.setUpdateTime(new Date());
//        //修改id
//        Employee attribute = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
//        employee.setUpdateUser(attribute.getId());
        employeeMapper.updateById(employee);
    }
}



















